package com.vehicle.service.config;

import cn.hutool.core.convert.Convert;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.vehicle.domains.entity.SystemConfigEntity;
import com.vehicle.exception.VehicleAccessException;
import com.vehicle.mapper.SystemConfigMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SystemConfigService {
    @Resource
    private SystemConfigMapper systemConfigMapper;

    private final Cache<String,Object> cache= CacheBuilder.newBuilder()
            .expireAfterAccess(5, TimeUnit.MINUTES)
            .maximumSize(10000L)
            .build();

    public <T> T get(SystemConfigItem<T> item) {
        String key = item.getKey();
        //先判断缓存中是否有数据
        Object cached = cache.getIfPresent(key);
        if (cached != null) {
            return item.getClazz().cast(cached);
        }
        String value = systemConfigMapper.getValue(key);
        if (value == null) {
            cache.put(key,item.getDefValue());
            return item.getDefValue();
        }
        T convert = Convert.convert(item.getClazz(), value);
        cache.put(key, convert);
        return convert;
    }
    public void removeCache(String key) {
        cache.invalidate(key);
    }
    public SystemConfigEntity selectByKey(String key) {
        return systemConfigMapper.selectByKey(key);
    }

    public void insert(SystemConfigEntity systemConfigEntity) {
        try {
            systemConfigMapper.insert(systemConfigEntity);
        } catch (VehicleAccessException e) {
            throw VehicleAccessException.DATA_EXIST.newInstance("配置已存在");
        }
    }

    public void updateByKey(SystemConfigEntity updateSystemConfigEntity) {
        int i = systemConfigMapper.updateByKey(updateSystemConfigEntity);
        if (i == 0) {
            throw VehicleAccessException.DATA_NOT_EXIST.newInstance("更新配置到数据库失败");
        }
    }
}
